package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class OrderReceiver {
    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentFeignClient paymentFeignClient;

    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void closeOrder(Long orderId, Message message, Channel channel) {
        try {
            if (orderId != null) {
                OrderInfo orderInfo = orderService.getById(orderId);
                if (orderInfo != null && "UNPAID".equals(orderInfo.getOrderStatus()) &&
                        "UNPAID".equals(orderInfo.getProcessStatus())) {
                    PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    //判断是否有支付信息
                    if (paymentInfo!=null && "UNPAID".equals(paymentInfo.getPaymentStatus())){
                        //  判断是否有alipay交易记录
                        Boolean exist = paymentFeignClient.checkPayment(orderId);
                        //  判断是否存在交易记录
                        if (exist){
                            //  调用关闭交易记录方法判断
                            Boolean result = paymentFeignClient.closePay(orderId);
                            //  关闭成功！
                            if (result){
                                log.info("这个订单没有支付：{} " , orderId);
                                //  说明用还未支付 ，关闭支付宝+paymentInfo+orderInfo;
                                orderService.execExpiredOrder(orderId,"2");
                            }else {
                                //  关闭失败！支付成功.
                                log.info("这个订单支付成功：{} ", orderId);
                            }

                        } else {
                            log.info("关闭 orderInfo paymentInfo 信息 {}：", orderId);
                            //   不存在支付宝交易记录.
                            //  可能需要关闭orderInfo+paymentInfo;
                            orderService.execExpiredOrder(orderId,"2");
                        }
                    } else {
                        log.info("关闭 orderInfo 信息 {}：", orderId);
                        //  没有本地交易记录.只有orderInfo
                        //  调用取消订单方法
                        //  orderService.execExpiredOrder(orderId); // 更改订单状态+更改本地交易记录状态。
                        orderService.execExpiredOrder(orderId,"1");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    //退款订单时
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER_CLOSED, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER_CLOSED),
            key = {MqConst.ROUTING_ORDER_CLOSED}
    ))
    public void orderClosed(Long orderId, Message message, Channel channel) {
        //  判断当前orderId
        try {
            if (orderId != null) {
                //  查询订单对象
                OrderInfo orderInfo = orderService.getById(orderId);
                if (orderInfo != null && !"CLOSED".equals(orderInfo.getOrderStatus()) && !"CLOSED".equals(orderInfo.getProcessStatus())) {
                    //  调用关闭订单方法.
                    orderService.updateOrder(orderId, ProcessStatus.CLOSED);
                }

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    //支付成功
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void paySuccessUpdateOrder(Long orderId, Message message, Channel channel) {
        //  判断当前orderId
        try {
            if (orderId != null) {
                //  查询订单对象
                OrderInfo orderInfo = orderService.getById(orderId);
                if (orderInfo != null && !"UNPAID".equals(orderInfo.getOrderStatus()) && !"UNPAID".equals(orderInfo.getProcessStatus())) {
                    //  调用修改的订单状态的方法
                    orderService.updateOrder(orderId, ProcessStatus.PAID);
                    //改库存方法
                    orderService.sendDeductStockMsg(orderId);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    //减库存完毕后更改订单状态

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            key = MqConst.ROUTING_WARE_ORDER
    ))
    public void processDeductStockResult(String stockJsonStr, Message message, Channel channel) {
        try {
            Map map = JSONObject.parseObject(stockJsonStr, Map.class);
            String orderId = (String) map.get("orderId");
            String status = (String) map.get("status");
            if ("DEDUCTED".equals(status)) {
                orderService.updateOrder(Long.parseLong(orderId),ProcessStatus.NOTIFIED_WARE);

            } else {
                //扣减失败-方案：提供定时任务扫描订单中处理状态为：库存异常。将这些订单作为预警订单提醒工作人员处理
                orderService.updateOrder(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
            }
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        }
        //  手动确认
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
